import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import basicSsl from '@vitejs/plugin-basic-ssl';
import SRI from 'unplugin-sri/vite';
import path from 'path';
import vueJsx from '@vitejs/plugin-vue-jsx';

//直接获取文件的text
function rawTransform(fileRegex: Array<RegExp>): {
  name: string;
  transform: (src: string, id: string) => string | void;
} {
  return {
    name: 'get-file-raw',
    transform(src, id): string | void {
      if (fileRegex.filter((re) => re.test(id)).length > 0) {
        return `export default ${JSON.stringify(src)}`;
      }
    }
  };
}

// 视频文件处理
const videoExt = ['.mp4', '.avi', '.wmv', '.ram', '.mpg', '.mpeg', '.m3u8'];
// 音频文件处理
const audioExt = ['.mp3', '.flac', '.wav', '.aac', '.ape', '.m4a'];
// 图片文件处理
const imgExt = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'];
// 字体文件处理
const fontExt = ['.ttf', '.otf', '.woff', '.woff2', '.eot'];

// https://vitejs.dev/config/
export default ({ mode }: any) => {
  const env = loadEnv(mode, process.cwd());
  return defineConfig({
    envDir: './env',
    server: {
      port: 8086,
      open: true,
      proxy: {
        '/api': {
          target: env.VITE_APP_API,
          // 指示代理服务器在转发请求时是否应该修改请求头中的 Host 字段。
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    plugins: [
      vue(),
      basicSsl(),
      SRI({}),
      vueJsx(), // jsx 格式支持
      rawTransform([/\.bpmn$/]),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        imports: ['vue'],
        dts: 'src/types/auto-imports.d.ts'
      }),
      Components({
        resolvers: [ElementPlusResolver()],
        dts: 'src/types/components.d.ts'
      })
    ],
    build: {
      outDir: 'dist/workflow',
      copyPublicDir: true,
      rollupOptions: {
        output: {
          // 静态资源（图片/字体等）输出配置
          assetFileNames: (assetInfo) => {
            const ext = assetInfo.name?.split('.').pop() || '';
            const baseName = assetInfo.name?.split('.').shift() || '';

            // CSS 文件处理
            if (ext === 'css') {
              return 'css/[name]-[hash].[ext]';
            }

            // 字体文件处理
            if (fontExt.includes(`.${ext}`.toLowerCase())) {
              return `assets/font/${baseName}-[hash].[ext]`;
            }

            // 图片文件处理
            if (imgExt.includes(`.${ext}`.toLowerCase())) {
              return `assets/imags/${baseName}-[hash].[ext]`;
            }

            // 视频文件处理
            if (videoExt.includes(`.${ext}`.toLowerCase())) {
              return `assets/video/${baseName}-[hash].[ext]`;
            }

            // 音频文件处理
            if (audioExt.includes(`.${ext}`.toLowerCase())) {
              return `assets/audio/${baseName}-[hash].[ext]`;
            }

            // 其他未分类资源
            return 'assets/other/[name]-[hash].[ext]';
          },

          // JS 代码输出配置
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js'
        }
      },
      minify: 'terser',
      terserOptions: {
        // 在打包代码时移除 console、debugger 和 注释
        compress: {
          drop_console: true, // 生产环境时移除console
          drop_debugger: false // 生产环境时移除debugger
        },
        format: {
          comments: false // 删除注释comments
        }
      }
    },
    resolve: {
      alias: [
        {
          find: '@',
          replacement: path.resolve(__dirname, 'src/')
        }
      ],
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.scss', '.css']
    },
    optimizeDeps: {
      //声明深度路径模块
      include: [
        'bpmn-js/lib/Modeler',
        'highlight.js',
        'codemirror',
        'codemirror/mode/xml/xml.js',
        'codemirror/addon/hint/xml-hint.js',
        'bpmn-js/lib/features/label-editing/LabelUtil.js'
      ]
    }
  });
};
